<?php

namespace tmcore\services\notice;

use app\common\model\notice\UserNoticeLog;
use tmcore\traits\ErrorTrait;
use tmcore\traits\TransTrait;

abstract class BaseNotice
{
    use ErrorTrait;
    use TransTrait;

    /**
     * 消息发送成功
     * @param $id
     * @param $send_time
     * @return UserNoticeLog
     */
    protected function sendSuccess($id, $send_time = 0) {
        return UserNoticeLog::where(['id' => $id])->update(['send_time' => $send_time?:time(), 'status' => 1]);
    }

    /**
     * 消息发送失败
     * @param $id
     * @param $err_msg
     * @return UserNoticeLog
     */
    protected function sendFail($id, $err_msg) {
        return UserNoticeLog::where(['id' => $id])->update(['error' => $err_msg, 'send_time' => 0, 'status' => 2]);
    }

    /**
     * 替换模板变量
     * @param array $params
     * @param string $content
     * @return string
     */
    protected function getContent(array $params, string $content): string
    {
        foreach ($params as $item => $val) {
            $search_replace = '${' . $item . '}';
            $content = str_replace($search_replace, $val, $content);
        }
        return (string)$content;
    }

    /**
     * 发送消息
     * @param $config
     * @param $params
     * @param bool $is_async
     * @return mixed
     */
    abstract public function send($config, $params, $is_async = false);
}